package com.haojiang.mh.utils

import android.Manifest.permission.ACCESS_WIFI_STATE
import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import androidx.annotation.RequiresPermission
import java.io.DataOutputStream
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList

/**
 *
 *
 * Created by ZapFive on 2019-05-25.
 *
 * wuzhuang@mirahome.me
 */
object NetUtil {

    /**
     * 判断 wifi 是否连接状态
     *
     */
    fun isWifiConnected(ctx: Context): Boolean {
        val cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val ni = cm.activeNetworkInfo
        return ni != null && ni.type == ConnectivityManager.TYPE_WIFI
    }

    /**
     * 判断 wifi 是否打开
     */
    @RequiresPermission(ACCESS_WIFI_STATE)
    fun getWifiEnabled(ctx: Context): Boolean {
        val wm = ctx.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        return wm.isWifiEnabled
    }

    /**
     * 判断 wifi 数据是否可用
     */
    fun isWifiAvailable(ctx: Context): Boolean {
        return getWifiEnabled(ctx) && isAvailableByPing()
    }

    /**
     * 判断网络是否可用
     */
    fun isAvailableByPing(): Boolean {
        val ip = "223.5.5.5" // 阿里云服务
        return execCmd(arrayOf(String.format("ping -c 1 %s", ip)), false) == 0
    }

    private fun execCmd(commands: Array<String>, isRooted: Boolean): Int {
        var result = -1
        if (commands.isNullOrEmpty()) {
            return result
        }
        val lineSep = System.getProperty("line.separator")
        var process: Process? = null
        var os: DataOutputStream? = null
        try {
            process = Runtime.getRuntime().exec(if (isRooted) "su" else "sh")
            os = DataOutputStream(process.outputStream)
            for (command in commands) {
                os.write(command.toByteArray())
                os.writeBytes(lineSep)
                os.flush()
            }
            os.writeBytes("exit$lineSep")
            os.flush()
            result = process.waitFor()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                os?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            process?.destroy()
        }
        return result
    }

    /**
     * 获取2.4G频段的WiFi列表
     */
    fun getWifiList(ctx: Context): List<ScanResult> {
        val wm = ctx.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val scanWifiList = wm.scanResults ?: return ArrayList()
        val linkedMap = LinkedHashMap<String, ScanResult>()
        if (scanWifiList.isNotEmpty()) {
            for (scanResult in scanWifiList) {
                if (scanResult.SSID.isNullOrEmpty()) continue
                if (!is24GHzWifi(scanResult.frequency)) continue
                if (linkedMap.contains(scanResult.SSID)) {
                    if (scanResult.level > linkedMap[scanResult.SSID]!!.level) {
                        linkedMap[scanResult.SSID] = scanResult
                    }
                    continue
                }
                linkedMap[scanResult.SSID] = scanResult
            }
        }
        scanWifiList.clear()
        scanWifiList.addAll(linkedMap.values)
        return scanWifiList
    }

    /**
     * 判定是否为2.4G频段
     *
     * @param frequency frequency
     */
    private fun is24GHzWifi(frequency: Int): Boolean {
        return frequency in 2401..2499
    }

    /**
     * 获取当前ss_id
     *
     * @return wifi名称
     */
    fun getSSID(ctx: Context): String? {
        if (isWifiConnected(ctx)) {
            val wm = ctx.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
            val info = wm.connectionInfo
            var ssid: String? = info.ssid
            if (ssid != null) {
                ssid = ssid.replace("\"".toRegex(), "")
                if ("0x" == ssid || "<unknown ssid>".equals(ssid, ignoreCase = true)) {
                    ssid = ""
                }
            }
            return ssid
        }
        return ""
    }

    /**
     * 打开WiFi
     */
    fun openWiFi(ctx: Context): Boolean {
        val wm = ctx.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        if (wm.isWifiEnabled) return true
        return wm.setWifiEnabled(true)
    }

    /**
     * 打开且扫描WiFi
     */
    fun openAndScanWiFi(ctx: Context) {
        val wm = ctx.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        if (!wm.isWifiEnabled) {
            wm.isWifiEnabled = true
        }
        wm.startScan()
    }

    /**
     * 打开且扫描WiFi
     */
    fun scanWiFi(ctx: Context) {
        val wm = ctx.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        wm.startScan()
    }
}